package cn.edu.njust.epms.interceptor;

import cn.edu.njust.epms.common.Resp;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@Order(214783646)
/**
 * 拦截器   用于阻止未登录访问页面（功能待完善）
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("user");
//        if("OPTIONS".equals(request.getMethod().toUpperCase()))
//            return true;
//        System.out.println(request.getRequestURI());
        if(user == null){
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            String s = JSONObject.toJSONString(Resp.error("请先登录！"));
            response.getWriter().write(s);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
